package com.vogue.flowmeter.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.vogue.flowmeter.R;
import com.vogue.flowmeter.api.entity.ApiRecordEntity;
import com.vogue.flowmeter.api.entity.BaseResponse;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import com.vogue.flowmeter.ui.adapter.BaseRecyclerAdapter;
import com.vogue.flowmeter.ui.adapter.SmartViewHolder;
import com.vogue.flowmeter.util.DateUtils;
import com.vogue.flowmeter.util.DeviceIdUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 记录
 */
public class NotificationsFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener {


    private SmartRefreshLayout smartRefreshLayout;

    private BaseRecyclerAdapter<ApiRecordEntity> mAdapter;

    private Integer page = 1;
    private Integer size = 10;


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData(true);
            }
        }, 1000);

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData(false);
            }
        }, 1000);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_notifications, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View root, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(root, savedInstanceState);

        RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
        if (recyclerView != null) {
            recyclerView.setNestedScrollingEnabled(false);
            //RecyclerView的分割线
            //recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
            recyclerView.setAdapter(mAdapter = new BaseRecyclerAdapter<ApiRecordEntity>(R.layout.record_list_item) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, ApiRecordEntity model, int position) {

                    holder.text(R.id.tv_operationName, model.getOperationName());
                    holder.text(R.id.tv_createTime, DateUtils.getTime(model.getCreateTime()));
                    holder.text(R.id.tv_data, model.getData());
                    //设置组件字体颜色
                    //holder.textColorId(android.R.id.text2, R.color.colorTextAssistant);

                }
            });
        }

        smartRefreshLayout = (SmartRefreshLayout) root.findViewById(R.id.refreshLayout);
        if (smartRefreshLayout != null) {
            smartRefreshLayout.setRefreshHeader(new ClassicsHeader(this.getActivity()));
            smartRefreshLayout.setRefreshFooter(new ClassicsFooter(this.getActivity()));

            smartRefreshLayout.autoRefresh();
            smartRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
            smartRefreshLayout.setOnRefreshListener(this);
            smartRefreshLayout.setOnLoadMoreListener(this);
        }


    }

    /**
     * @param refresh true 参数重置到初始值 false 加载更多数据
     */
    private void loadData(boolean refresh) {
        if (refresh) {
            page = 1;
            size = 10;
        } else {
            page++;
        }
        String deviceId = DeviceIdUtil.getDeviceId(requireActivity());
        HashMap<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("size", size);
        params.put("deviceId", deviceId);

        NetWorkManager
                .getInstance()
                .getBleApiService()
                .getRecords(params)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {

                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        try {
                            String body = response.string();
                            BaseResponse<List<ApiRecordEntity>> res = JSON.parseObject(body, new TypeReference<BaseResponse<List<ApiRecordEntity>>>(ApiRecordEntity.class) {
                            });
                            if (refresh) {
                                mAdapter.refresh(res.getData());
                                if (res.getData().size() < 9) {
                                    smartRefreshLayout.finishRefreshWithNoMoreData();
                                } else {
                                    smartRefreshLayout.finishRefresh();
                                }
                            } else {
                                mAdapter.loadMore(res.getData());
                                if (res.getData().size() < 10) {
                                    smartRefreshLayout.finishLoadMoreWithNoMoreData();
                                } else {
                                    smartRefreshLayout.finishLoadMore();
                                }
                            }
                        } catch (IOException i) {
                            Toast.makeText(requireActivity(), i.getMessage(), Toast.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(NotificationsFragment.class.getName(), e.getMessage());

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}